package api

import (
	"strconv"
	"strings"
	"vblog/apps/user"
	"vblog/conf"
	"vblog/ioc"
	"vblog/middleware"
	"vblog/response"

	"github.com/gin-gonic/gin"
)

func init() {
	ioc.Api.Registry(user.AppName, &ApiHandler{})
}

type ApiHandler struct {
	user user.Service
}

func (a *ApiHandler) Init() error {
	a.user = ioc.Controller.Get(user.AppName).(user.Service)
	appRouter := conf.C().APP.RootRouter().Group(user.AppName)
	a.Registry(appRouter)
	return nil
}

func (a *ApiHandler) Registry(appRouter gin.IRouter) {
	appRouter.Group("/", a.CreateUser)

	appRouter.Use(middleware.Auth)
	appRouter.Group("/:id", a.DescribeUser)
}

func (a *ApiHandler) CreateUser(ctx *gin.Context) {
	req := user.NewCreateUserRequest()
	res, err := a.user.CreateUser(ctx, req)
	if err != nil {
		response.Failed(ctx, err)
	}
	response.Success(ctx, res)

}
func (a *ApiHandler) QueryUser(ctx *gin.Context) {
	// 获取参数
	req := user.NewQueryUserRequest()
	res, err := a.user.QueryUser(ctx, req)
	if err != nil {
		response.Failed(ctx, err)
	}
	response.Success(ctx, res)

}
func (a *ApiHandler) DescribeUser(ctx *gin.Context) {
	// 获取参数
	// 获取id
	req := user.NewDescribeUserRequest()
	req.UserId, _ = strconv.Atoi(strings.TrimSpace(ctx.Param("id")))

	res, err := a.user.DescribeUser(ctx, req)
	if err != nil {
		response.Failed(ctx, err)
	}
	response.Success(ctx, res)

}
